import { queryCourse, removeCourse, addCourse } from '../services/api';

export default {
  namespace: 'course',

  state: {
    fulllist: [],
    data: {
      list: [],
      pagination: {},
    },
    loading: true,
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(queryCourse, payload);
      const { data, total, current_page } = response;
      yield put({
        type: 'list',
        payload: {
          data,
          pagination: {
            total,
            current: current_page,
            pageSize: 10,
            showSizeChanger: false,
          },
        },
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    *fetchAll({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(queryCourse, payload);
      const { data } = response;
      yield put({
        type: 'fulllist',
        payload: data,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    *add({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(addCourse, payload);
      yield put({
        type: 'save',
        payload: response
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });

      if (callback) callback(response);
    },
    *remove({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(removeCourse, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });

      if (callback) callback();
    },
  },

  reducers: {
    list(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    fulllist(state, action) {
      return {
        ...state,
        fulllist: action.payload,
      };
    },
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
  },
};
